import serial
import threading
import time

# 串口配置参数
port = 'COM30'  # 串口端口号，根据实际情况修改
baudrate = 115200  # 波特率
timeout = 1000  # 读取超时时间

# 打开串口
ser = serial.Serial(port, baudrate, timeout=timeout)

# 用于接收串口数据的线程函数
def receive_data():
    while True:
        if ser.in_waiting > 0:  # 检查串口缓冲区是否有数据
            data = ser.read(ser.in_waiting)  # 读取所有可用数据
            received_text = data.decode('utf-8', errors='ignore')  # 解码接收到的数据
            print(f"Received data: {received_text}", end='')  # 打印接收到的数据

            # 检测是否接收到特定字符
            if '>' in received_text:
                print("Detected '>' character, sending '123'")
                ser.write(b'123')  # 自动发送字符串 '123'

# 启动接收数据的线程
receive_thread = threading.Thread(target=receive_data)
receive_thread.daemon = True  # 设置为守护线程，当主线程退出时，接收线程也会退出
receive_thread.start()

# 主线程用于发送数据
try:
    while True:
        send_data = input("Enter data to send: ")  # 获取用户输入的数据
        ser.write(send_data.encode('utf-8'))  # 将数据发送到串口
        time.sleep(0.1)  # 稍作延时，避免发送过快
except KeyboardInterrupt:
    print("Program terminated by user.")
finally:
    ser.close()  # 关闭串口